"""
KNN
灰度：0-1
分类：0-9
入口在最后
"""

# train:60000
# test:500

# acc: 0.956
# time: 1666s

import pandas as pd
import numpy as np
import time
from collections import Counter


def loadData(fileName):
    data = pd.read_csv(fileName, header=None)
    data = data.values  # we use numpy

    y_label = data[:, 0]
    x_label = np.mat(data[:, 1:])

    return x_label/255.0, y_label


def calcD(x1, x2):
    return np.sqrt(np.sum(np.square(x1-x2)))

# d为新的一个点，含分类


def findClass(x_train, y_train, d, k):
    distances = []
    for x in x_train:
        distances.append(calcD(x, d))

    minK = np.argsort(np.array(distances))[:k]
    # minK 为数据集中的index

    result = []
    for i in range(k):
        result.append(y_train[minK[i]])

    belong = Counter(result).most_common(1)[0][0]

    return belong


def test(x_train, y_label, x_test, y_test, k):
    acc_num = 0
    acc = 0
    for i in range(500):
        cluster = findClass(x_train, y_train, x_test[i], k)
        if cluster == y_test[i]:
            acc_num += 1
        print(f'{i}th data: pred={cluster}, cluster = {y_test[i]}')
        print('acc=', acc_num/(i+1))

# 入口


if __name__ == '__main__':
    start = time.time()

    x_train, y_train = loadData('Mnist/mnist_train.csv')

    x_test, y_test = loadData('Mnist/mnist_test.csv')

    test(x_train, y_train, x_test, y_test, k=20)

    end = time.time()

    print('run time:', end-start)
